<template>
  <div>

      <div style="margin-bottom:15px">
        <el-input v-model="params.tutorName" style="width:200px" placeholder="Enter the tutor name"></el-input>
        <el-input v-model="params.typeName" style="width:200px;margin-left:5px" placeholder="Enter category"></el-input>
        <el-button type="warning" style="margin-left:10px" @click="findBySearch()">query</el-button>
        <el-button type="warning" style="margin-left:10px" @click="reset()">clear</el-button>
        <el-button type="primary" style="margin-left:10px" @click="add()" v-if="user.role === 'ROLE_ADMIN'">add</el-button>
      </div>
      <div>
        <el-table :data="tableData" style="width: 100%">
          
          <el-table-column prop="tutorName" label="教师姓名" ></el-table-column>
          
          <el-table-column prop="studentName" label="学生姓名"></el-table-column>
          <el-table-column prop="typeName" label="研究方向"></el-table-column>


            <el-table-column label="上传中期检查">
              <template slot-scope="scope">
                <el-upload action="http://localhost:8080/api/files/upload" :on-success="successUpload">
                  <el-button size="small" type="primary">点击上传</el-button>
                </el-upload>
              </template>
            </el-table-column>

          <el-table-column label="下载中期检查">
            <template slot-scope="scope">
              <el-button type="primary"  @click="downPDF(scope.row)">点击下载</el-button>
            </template>
          </el-table-column>


          <el-table-column label="中期检查分数">
            <template slot-scope="scope">
              {{ getScore(scope.row) || '加载中...' }}

            </template>
          </el-table-column>


          <el-table-column prop="time" label="预订时间"></el-table-column>
          
          <el-table-column  label="操作" width="250px">
            <template slot-scope="scope">
              <el-button type="danger" @click="audit(scope.row)" v-if="user.role !=='ROLE_STUDENT'">打分</el-button>

              
              <el-popconfirm title="Are you sure to delete?" @confirm="del(scope.row.id)">
                <el-button slot="reference" type="danger" style="margin-left:5px" v-if="user.role === 'ROLE_ADMIN'">删除</el-button>
              </el-popconfirm>
              <!-- <el-button type="danger">删除</el-button> -->
            </template>
          </el-table-column>
        </el-table>
      </div>

        <div style="margin-top: 10px;">
          
                <el-pagination
                  @size-change="handleSizeChange"
                  @current-change="handleCurrentChange"
                  :current-page="params.pageNum"
                  :page-sizes="[5, 10, 15, 20]"
                  :page-size="params.pageSize"
                  layout="total, sizes, prev, pager, next, jumper"
                  :total="total">
                </el-pagination>
        </div>


        <!-- 审核信息 -->

        <div>

          <div>
            <el-dialog title="请打分（0-20分）" :visible.sync="auditVisible" width="55%">
              <el-form :model="form">
                <el-form-item label="评分" label-width="15%">
                  <el-input
                      v-model.number="form.inspectScore"
                      type="number"
                      step="0.1"
                      min="0"
                      max="20"
                      placeholder="请输入分数"
                      style="width:90%"
                  ></el-input>
                </el-form-item>
              </el-form>

              <div slot="footer" class="dialog-footer">
                <el-button @click="auditVisible = false">取消</el-button>
                <el-button type="primary" @click="submitScore()">确定</el-button>
              </div>
            </el-dialog>
          </div>

        </div>

        <!-- 评价助教 -->
        <div>

          <el-dialog title="请评价家教" :visible.sync="dialogFormVisible" width="50%" @opened="initWangEditor('')">
            <el-form :model="form">

              <el-form-item  label-width="8%">
                <div id="editor" style="width:90%"></div>
              </el-form-item>

            </el-form>
            <div slot="footer" class="dialog-footer">
              <el-button @click="dialogFormVisible = false">取消</el-button>
              <el-button type="primary" @click="evaluate()">确定</el-button>
            </div>
          </el-dialog>

        </div>

  </div>
</template>

<script>
import request from '@/utils/request'

import E from 'wangeditor'

let editor


function initWangEditor(content) {
  setTimeout(() => {
    if (editor) {
      editor.destroy(); // 销毁旧实例
    }
    editor = new E('#editor');
    editor.config.placeholder = '请输入内容';
    editor.config.uploadFileName = 'file';
    editor.config.uploadImgServer = 'http://localhost:8080/api/files/wang/upload';
    editor.create();
    editor.txt.html(content || '');
  }, 100);
}

    export default {
      data() {
        return {
          params:{
            tutorName:'',
            typeName:'',
            pageNum:1,
            pageSize:5
          },
          tableData: [],
          total: 0,
          dialogFormVisible: false,
          editorVisible:false,
          viewData:'',
          typeObjs:[],
          auditVisible: false,
          form:{},
          user:localStorage.getItem("user")?JSON.parse(localStorage.getItem("user")):{},

          tutorName:''
        }
      },
      //页面加载的时候，做一些事情，在created里面
      created(){
         this.findBySearch();
         this.findTypes();
      },
      //定义一些页面上空间触发的事件调用的方法
      methods:{ 
        findBySearch(){
          request.get("/hire/search",{
            params:this.params
          }).then(res =>{
            if(res.code === '0'){
              this.tableData = res.data.list
              this.total = res.data.total
            }else{
                  this.$message.error(res.msg)
            }
          })
        },
        add(){
          this.form = {}
          this.dialogFormVisible = true
        },
        review(obj){
          this.form = obj,
          initWangEditor("")
          this.dialogFormVisible = true
          //alert(this.form.tutorId)
        },
        evaluate(){
          //alert(this.form.tutorId)
          //alert(this.form.tutorName)
          this.form.content = editor.txt.html()
          //alert(this.form.content)
          let param = {
            id:this.form.tutorId,
            content:this.form.content
          }
          

          request.put("/admin/evaluate",param).then(res =>{
            if(res.code === '0'){
                this.$message.success("Evaluation success")
                this.dialogFormVisible = false
                //this.auditVisible = false
                this.findBySearch()
            }else{
                
                this.$message.error(res.msg)
            }
          })

        },
        
        edit(obj){
          this.dialogFormVisible = true
          this.form = obj

        },
        reset(){
           this.params={
            pageNum:1,
            pageSize:5,
            name:'',
            author:''
           }
           this.findBySearch()
        },
        audit(obj){
          this.form = obj;
          this.auditVisible = true
        },
        submit(){
          request.post("/hire/audit",this.form).then(res =>{
            if(res.code === '0'){
                this.$message.success("Review successful")
                //this.dialogFormVisible = false
                this.auditVisible = false
                this.findBySearch()
            }else{
                
                this.$message.error(res.msg)
            }
          })
        },
        payment(obj){

          this.form = obj
          // alert(this.form.id)
          // alert(this.form.tutorId)

          let param = {
            id:this.form.id
          }
          
          request.get("/admin/getTutorInformation",{
               params: param
            }).then(res =>{
            if(res.code === '0'){
            
              this.paymentAmount = res.data.price
              this.tutorName = res.data.name
              this.payVisible = true;
            }else{
                  this.$message.error("Failed to obtain tutoring information")
            }
          }).catch(error => {
            // 捕获请求错误
            console.error("Request failed:", error);
            this.$message.error("Network error or server is unreachable");
          });

          
        },
        handlePayment(){
            request.put("/hire/payment",this.form).then(res =>{
              if(res.code === '0'){
                  this.$message.success("Pay Success")
                  this.payVisible = false
                  this.findBySearch()
              }else{
                  
                  this.$message.error(res.msg)
              }
            })
        },
        successUpload(res){
          console.log(res);
          this.form.inspect = res.data.fileUrl;    // 保存URL到img字段
          this.form.id = this.user.id;
          //弹窗，user.id

          //this.form.imgName = res.data.fileName; // 保存文件名到fileName字段
          request.post("/admin/inspect",this.form).then(res =>{
            if(res.code === '0'){
              this.$message.success("上传成功")
              this.findBySearch()
            }else{
              this.$message.error(res.msg)
            }
          })
        },
        downPDF(obj) {
          this.form = obj;
          let params = {
            name: this.form.studentName
          }
          //let pdfUrl;
          request.get("/admin/getInspect",{
               params: params
            }).then(res =>{
              if(res.code === '0'){

                const pdfUrl = res.data;

                if (!pdfUrl) {
                  this.$message.warning("暂无PDF文件可下载");
                  return;
                }

                // 1. 处理URL中的特殊字符（确保链接有效）
                const encodedUrl = encodeURI(pdfUrl);

                // 2. 从URL中提取OSS原始文件名（不做任何自定义）
                // 例如：https://bucket.oss-cn-beijing.aliyuncs.com/docs/简历2023.pdf → 提取“简历2023.pdf”
                const fileName = pdfUrl.split("/").pop(); // 从URL最后一段截取文件名

                // 3. 创建a标签下载（download属性直接使用提取的原始文件名）
                const link = document.createElement("a");
                link.href = encodedUrl;
                link.download = decodeURIComponent(fileName); // 解码URL中的特殊字符（如中文），还原原始文件名

                // 4. 触发下载并清理
                document.body.appendChild(link);
                link.click();
                setTimeout(() => {
                  document.body.removeChild(link);
                }, 100);

              }else{
                this.$message.error(res.msg);
              }

          }).catch(error => {
            console.error("下载失败:", error);
            this.$message.error("下载过程中发生错误");
          });

        },

        submitScore() {
          console.log('提交评分:', this.form.inspectScore);
          //this.form.id = this.user.id;
          this.form.name = this.form.studentName;
          request.post("/admin/inspectScore",this.form).then(res =>{
            if(res.code === '0'){
              this.$message.success("打分成功")
              this.findBySearch()
            }else{
              this.$message.error(res.msg)
            }
          })



          this.auditVisible = false;
        },

        getScore(row) {
          // 1. 若已有分数，直接返回（避免重复请求）
          if (row.proposalScore !== undefined && row.proposalScore !== '获取失败' && row.proposalScore !== '网络错误') {
            return row.proposalScore;
          }

          // 2. 若无分数，发送请求（添加标识避免重复请求）
          if (!row.isLoadingScore) { // 用isLoadingScore标记是否正在请求
            row.isLoadingScore = true; // 标记为正在请求
            let param = {
              name: row.studentName // 注意：这里用row.studentName，而非this.form.studentName（避免this.form被覆盖）
            };
            request.get("/admin/getInspectScore", { params: param })
                .then(res => {
                  row.isLoadingScore = false; // 清除请求标记
                  if (res.code === '0') {
                    // 用this.$set强制触发响应式更新
                    this.$set(row, 'proposalScore', res.data);
                  } else {
                    this.$set(row, 'proposalScore', '获取失败');
                    this.$message.error(res.msg || '获取分数失败');
                  }
                })
                .catch(error => {
                  row.isLoadingScore = false;
                  console.error('获取分数出错:', error);
                  this.$set(row, 'proposalScore', '网络错误');
                  this.$message.error('网络错误，请稍后重试');
                });
          }

          // 3. 请求未完成时，返回当前值（初始为undefined，显示“加载中...”）
          return row.proposalScore;
        },
        paymessage(){
          this.message.success("Pay Success")
        },
        handleSizeChange(pageSize){
           this.params.pageSize = pageSize
           this.findBySearch()
        },
        handleCurrentChange(pageNum){
          this.params.pageNum = pageNum
           this.findBySearch()
        },
        del(id){
          request.delete("/reserve/"+id).then(res =>{
            if(res.code === '0'){
              this.$message.success("Delete successfully")
              this.findBySearch()
            }else{
              this.$message.error(res.msg)
            }
          })
        },
  
      }
    }
  </script>